package net.homeip.dometec.autodownloadrcsqt;

import static net.homeip.dometec.autodownloadrcsqt.MainWindow.sdf;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.FocusEvent;
import java.awt.event.FocusListener;
import java.awt.event.KeyEvent;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Calendar;
import java.util.Properties;

import javax.swing.ButtonGroup;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JFileChooser;
import javax.swing.JFormattedTextField;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JPasswordField;
import javax.swing.JRadioButton;
import javax.swing.JTextField;
import javax.swing.SpringLayout;

public class ConfigWindow implements ActionListener, MouseListener, FocusListener {

	private File conf;
	private JFrame frame;
	private Properties properties;
	private JTextField textFieldEmail;
	private JPasswordField textFieldPassword;
	private JTextField textFieldOutdir;
	private JTextField textFieldMindate;
	private ButtonGroup radioGroup;
	private JRadioButton allButton;
	private JRadioButton lastButton;
	private JCheckBox chkCloseOnEnd;
	private Boolean startWindowMain;

	public ConfigWindow(File conf) {
		this(conf, false);
	}

	public ConfigWindow(File conf, Boolean startWindowMain) {

		this.startWindowMain = startWindowMain;
		this.conf = conf;
		properties = new Properties();

		if (conf.isFile()) {
			try {
				properties.load(new FileInputStream(conf));
			} catch (FileNotFoundException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}

		// Create and populate the panel.
		JPanel p = new JPanel(new SpringLayout());

		JLabel l = new JLabel("Email: ", JLabel.TRAILING);
		p.add(l);
		textFieldEmail = new JTextField(10);
		l.setLabelFor(textFieldEmail);
		p.add(textFieldEmail);

		l = new JLabel("Password: ", JLabel.TRAILING);
		p.add(l);
		textFieldPassword = new JPasswordField(10);
		l.setLabelFor(textFieldPassword);
		p.add(textFieldPassword);

		l = new JLabel("Directory di download: ", JLabel.TRAILING);
		p.add(l);
		textFieldOutdir = new JTextField();
		l.setLabelFor(textFieldOutdir);
		p.add(textFieldOutdir);
		textFieldOutdir.addMouseListener(this);
		textFieldOutdir.addFocusListener(this);

		l = new JLabel("Inizia a recuperare dal: ", JLabel.TRAILING);
		p.add(l);
		textFieldMindate = new JFormattedTextField(sdf);
		l.setLabelFor(textFieldMindate);
		p.add(textFieldMindate);

		l = new JLabel("Apri automaticamente:", JLabel.TRAILING);
		p.add(l);
		allButton = new JRadioButton("Tutte le edizioni appena scaricate");
		allButton.setMnemonic(KeyEvent.VK_B);
		allButton.setSelected(true);
		p.add(allButton);
		l = new JLabel("", JLabel.TRAILING);
		p.add(l);
		lastButton = new JRadioButton("Solo l'ultima");
		lastButton.setMnemonic(KeyEvent.VK_B);
		lastButton.setSelected(false);
		p.add(lastButton);

		radioGroup = new ButtonGroup();
		radioGroup.add(allButton);
		radioGroup.add(lastButton);

		l = new JLabel("Chiudi il programma alla fine: ", JLabel.TRAILING);
		p.add(l);
		chkCloseOnEnd = new JCheckBox();
		p.add(chkCloseOnEnd);

		l = new JLabel("", JLabel.TRAILING);
		p.add(l);
		JButton saveBtn = new JButton("Salva");
		saveBtn.addActionListener(this);
		p.add(saveBtn);

		// Lay out the panel.
		SpringUtilities.makeCompactGrid(p, 8, 2, // rows, cols
				6, 6, // initX, initY
				6, 6); // xPad, yPad

		// Create and set up the window.
		frame = new JFrame("SpringForm");

		if (startWindowMain)
			frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		else
			frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);

		frame.setTitle("Configurazione Download Automatico Fatto Quotidiano");

		// Set up the content pane.
		p.setOpaque(true); // content panes must be opaque
		frame.setContentPane(p);

		SpringUtilities.centerWindow(frame);

		// Display the window.
		frame.pack();
		frame.setVisible(true);

		String user = properties.getProperty("user");
		String pass = properties.getProperty("pass");
		String outdir = properties.getProperty("outdir");
		String mindate = properties.getProperty("mindate");
		String show = properties.getProperty("show");
		String closeonend = properties.getProperty("closeonend");

		if (user != null)
			textFieldEmail.setText(user);

		if (pass != null)
			textFieldPassword.setText(pass);

		if (outdir != null)
			textFieldOutdir.setText(outdir);

		if (mindate != null)
			textFieldMindate.setText(mindate);
		else {
			Calendar cal = Calendar.getInstance();
			cal.add(Calendar.DAY_OF_MONTH, -7);
			textFieldMindate.setText(sdf.format(cal.getTime()));
		}

		if ("last".equals(show)) {
			lastButton.setSelected(true);
		}

		if (new Boolean(closeonend)) {
			chkCloseOnEnd.setSelected(true);
		}

	}

	// Save
	public void actionPerformed(ActionEvent event) {

		properties.setProperty("user", textFieldEmail.getText());
		properties.setProperty("pass", new String(textFieldPassword.getPassword()));
		properties.setProperty("outdir", textFieldOutdir.getText());
		properties.setProperty("mindate", textFieldMindate.getText());
		properties.setProperty("closeonend", String.valueOf(chkCloseOnEnd.isSelected()));

		if (allButton.isSelected())
			properties.setProperty("show", "all");
		else
			properties.setProperty("show", "last");

		try {

			if (!(new File(textFieldOutdir.getText()).isDirectory())) {

				JOptionPane.showMessageDialog(frame, "La directory di download non è valida.");

			} else {

				HttpAccess httpAccess = new HttpAccess("CORSE", "CORRIEREFC", ".corriere.it");
				boolean result = httpAccess.autentica(textFieldEmail.getText(), new String(textFieldPassword.getPassword()));

				if (result) {

					properties.store(new FileOutputStream(conf), "Configurazione per il recupero dei Quotidiani RCS");
					frame.setVisible(false);
					frame.dispose();

					if (startWindowMain) {
						new Thread(new Runnable() {
							public void run() {
								new MainWindow();
							}
						}).start();
					}

				} else {
					JOptionPane.showMessageDialog(frame, "Email o password non validi.");
				}

			}

		} catch (Exception e) {
			e.printStackTrace();
		}

	}

	public void mouseClicked(MouseEvent e) {

		if (e.getSource().equals(textFieldOutdir)) {
			showFolderSelect();
		}

	}

	private void showFolderSelect() {
		JFileChooser chooser = new JFileChooser();
		chooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
		int ret = chooser.showDialog(null, "Segli cartella");
		if (ret == JFileChooser.APPROVE_OPTION) {
			File file = chooser.getSelectedFile();
			textFieldOutdir.setText(file.getAbsolutePath());
		}
	}

	public void focusGained(FocusEvent e) {
		if (e.getSource().equals(textFieldOutdir) && textFieldOutdir.getText().length() == 0) {
			showFolderSelect();
		}
	}

	public void mouseEntered(MouseEvent e) {
		// nothing to do
	}

	public void mouseExited(MouseEvent e) {
		// nothing to do
	}

	public void mousePressed(MouseEvent e) {
		// nothing to do
	}

	public void mouseReleased(MouseEvent e) {
		// nothing to do
	}

	public void focusLost(FocusEvent e) {
		// nothing to do
	}
}
